package com.guojian.http.handle.route;

import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.server.handle.HttpHandle;
import org.smartboot.http.utils.AntPathMatcher;

import com.google.common.base.Charsets;
import com.guojian.http.handle.config.RouteConfig;
import com.guojian.http.handle.service.HttpSmartServiceHandle;

/**
 * 路由处理器,解析请求的URL
 * @author guoJian
 *
 */
public class HttpSmartRouteHandle extends HttpHandle {

	private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

	/**
	 * 默认404
	 */
	public static final HttpHandle DEFAULT_HANDLE = new Http404Handle();

	public static final HttpHandle ERROR_HANDLE = new Http500Handle();

	/**
	 * 所有请求复用一个HttpServiceHandle
	 */
	private HttpSmartServiceHandle serviceHandle = new HttpSmartServiceHandle();

	@Override
	public void doHandle(HttpRequest request, HttpResponse response) throws Exception {
		String requestUri = request.getRequestURI();// ::/ccbHousing/a/b
		HttpHandle httpHandle = DEFAULT_HANDLE;
		for (Map.Entry<String, String> entity : RouteConfig.getRoutePatternUrl().entrySet()) {
			if (PATH_MATCHER.match(entity.getKey(), requestUri)) {
				String uriPath = PATH_MATCHER.extractPathWithinPattern(entity.getKey(), requestUri);//:: /**匹配的url
				httpHandle = serviceHandle.setTargetUrl(entity.getValue() + uriPath);
				break;
			}
		}
		httpHandle.doHandle(request, response);
	}

	public static void main(String[] args) {

		System.out.println("args = " + PATH_MATCHER.extractPathWithinPattern("/a/**", "/a/b/guojian?a=a"));

		System.out.println(PATH_MATCHER.match("/a/**", "http://localhost:8090/a/b/guojian?a=a"));

		//Map<String, String> a = PATH_MATCHER.extractUriTemplateVariables("{}", "/a/b/aa.txt");

		//System.out.println("JSON.toJSONString(a) = " + JSON.toJSONString(a));

		List<NameValuePair> list = URLEncodedUtils.parse("a=1&b=2&c=3", Charsets.UTF_8);
		for (NameValuePair nameValuePair : list) {
			System.out.println(nameValuePair.getName());
		}

	}

}
